package com.reef.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.reef.dao.BookRepository;
import com.reef.dto.BookDto;
import com.reef.entity.Book;
import com.reef.service.BookService;
@Service
public class BookServiceImpl implements BookService{
	@Autowired
   private BookRepository bookRepository;
	public List<Book> selAll() {
		// TODO Auto-generated method stub
		return bookRepository.findAll();
	}

	public Book save(Book book) {
		// TODO Auto-generated method stub
		return bookRepository.save(book);
	}

	public Page<Book> findByCondition(BookDto bDto, Pageable pageable) {
		Specification<Book> spec = getSpec(bDto);
		return bookRepository.findAll(spec, pageable);
	}
	/**
	 * 单独封装的方法
	 * @param tDto
	 * @return
	 */
	public Specification<Book> getSpec(final BookDto bDto) {
		return new Specification<Book>() {

			public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//创建SQL表达式
				Predicate p = criteriaBuilder.conjunction();
				//声明表达式的集合
				List<Expression<Boolean>> list = p.getExpressions();
				if (bDto.getIsbn()!=null && bDto.getIsbn()!="") {
					list.add(criteriaBuilder.equal(root.get("isbn").as(String.class),bDto.getIsbn() ));
				}
				if (bDto.getName()!=null && bDto.getName()!=" ") {
					list.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+bDto.getName()+"%"));
				}
				if (bDto.getPrice()!=null && bDto.getPrice()!=" ") {
					list.add(criteriaBuilder.like(root.get("price").as(String.class), "%"+bDto.getPrice()+"%"));
				}
				
				return p;
			}
		};
	}

	public Book updateBook(Book book) {
		// TODO Auto-generated method stub
		return bookRepository.save(book);
	}

	public Book insertBook(Book book) {
		// TODO Auto-generated method stub
		return bookRepository.save(book);
	}

	public int updateByNumber(int number, int lendnum, int book_id) {
		// TODO Auto-generated method stub
		return bookRepository.updateByNumber(number, lendnum, book_id);
	}

	public int updateByBookNumber(int number, int book_id) {
		// TODO Auto-generated method stub
		return bookRepository.updateByBookNumber(number, book_id);
	}
}
